/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FuUpPanel.java
 *
 * Created on 01/12/2011, 14:40:54
 */
package proj5labbd.graphics.funcionario;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

public class FuUpPanel extends OperationPanel {

    /** Creates new form FuUpPanel */
    public FuUpPanel(FuncionarioFrame frame, DBInterface dbInterface) {
        super(frame, dbInterface);
        initComponents();
        jbtUpdate.addActionListener(new FuncAction());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnInsert = new javax.swing.JPanel();
        jlbCPF = new javax.swing.JLabel();
        jftxtCPF = new javax.swing.JFormattedTextField();
        jlbNome = new javax.swing.JLabel();
        jtxtNome = new javax.swing.JTextField();
        jlbDate = new javax.swing.JLabel();
        jlbTipo = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtbTipoFu = new javax.swing.JTable();
        jftxtDate = new javax.swing.JFormattedTextField();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbUpdate = new javax.swing.JTable();
        jbtUpdate = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Atualização"));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jpnInsert.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros de atualização"));

        jlbCPF.setText("CPF");

        try {
            jftxtCPF.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtCPF.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        jlbNome.setText("Nome Completo");

        jlbDate.setText("Data de nascimento");

        jlbTipo.setText("Tipo de funcionário");

        jtbTipoFu.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane2.setViewportView(jtbTipoFu);

        try {
            jftxtDate.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        javax.swing.GroupLayout jpnInsertLayout = new javax.swing.GroupLayout(jpnInsert);
        jpnInsert.setLayout(jpnInsertLayout);
        jpnInsertLayout.setHorizontalGroup(
            jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnInsertLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jlbTipo)
                    .addGroup(jpnInsertLayout.createSequentialGroup()
                        .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jlbCPF, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jftxtCPF, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE)
                            .addComponent(jtxtNome, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlbNome, javax.swing.GroupLayout.Alignment.LEADING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jftxtDate, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jlbDate))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jpnInsertLayout.setVerticalGroup(
            jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnInsertLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbCPF)
                    .addComponent(jlbDate))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jftxtCPF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jftxtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jlbNome)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jtxtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jlbTipo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jtbUpdate.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jtbUpdate);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 488, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 181, Short.MAX_VALUE)
        );

        jbtUpdate.setText("Atualizar");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbtUpdate, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jpnInsert, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpnInsert, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jbtUpdate))
        );
    }// </editor-fold>//GEN-END:initComponents

    /*
     * Resgata as informações das tabelas que serão exibidas
     */
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        try {
            // TODO add your handling code here:
            setupTable();
        } catch (SQLException ex) {
            frame.printException(ex);
            JOptionPane.showMessageDialog(null, "Não foi possível resgatar os dados da tabela");
        }
    }//GEN-LAST:event_formComponentShown

    /*
     * Trata os eventos do mouse
     */
    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
        jtbTipoFu.clearSelection();
        jtbUpdate.clearSelection();
    }//GEN-LAST:event_formMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jbtUpdate;
    private javax.swing.JFormattedTextField jftxtCPF;
    private javax.swing.JFormattedTextField jftxtDate;
    private javax.swing.JLabel jlbCPF;
    private javax.swing.JLabel jlbDate;
    private javax.swing.JLabel jlbNome;
    private javax.swing.JLabel jlbTipo;
    private javax.swing.JPanel jpnInsert;
    private javax.swing.JTable jtbTipoFu;
    private javax.swing.JTable jtbUpdate;
    private javax.swing.JTextField jtxtNome;
    // End of variables declaration//GEN-END:variables
    
    /*
     * Formata a tabela funcionario
     */
    private void setupTable() throws SQLException {
        
        String [] titles = {"ID","Nome","Data de nascimento","CPF",
            "Salario","Cargo"};
        String [] fields = {"funcionario.idFu","funcionario.nomeCompletoFu","funcionario.dataNascimentoFu",
            "funcionario.cpfFu","funcionario.salarioFu","tipoFuncionario.descricaoTipoFu"};
        String [] params = {"tipoFuncionario.idTipoFu=funcionario.idTipoFu"};
        String [][] s = dbInterface.view(fields, params, new String[]{"funcionario","tipoFuncionario"});
        
        DefaultTableModel model = new DefaultTableModel(s,titles);
        jtbUpdate.setModel(model);
        
         String [] titlesTipo = {"ID","Salario","Tipo"};

        s = dbInterface.view(null, null, new String[]{"tipoFuncionario"});
        model = new DefaultTableModel(s,titlesTipo);
        jtbTipoFu.setModel(model);
    }
    
    class FuncAction implements ActionListener {
        
        /*
         * Controla os eventos de atualização
         */
        public void actionPerformed(ActionEvent e) {
            
            ArrayList<String> fields = new ArrayList<String>();
            
            if (jtxtNome.getText().trim().compareTo("") != 0) {
                fields.add("funcionario.nomeCompletoFu='"+jtxtNome.getText()+"'");
            }
            
            if (jftxtCPF.getText().compareTo("   .   .   -  ") != 0) {
                fields.add("funcionario.cpfFu='"+jftxtCPF.getText()+"'");
            }
            
            if (jftxtDate.getText().compareTo("  -  -    ") != 0) {
                fields.add("funcionario.dataNascimentoFu=TO_DATE('"
                        + jftxtDate.getText() +"','DD-MM-YYYY')");
            }
            
            if (jtbTipoFu.getSelectedRowCount() == 1) {
                fields.add("funcionario.idTipoFu="+
                        jtbTipoFu.getValueAt(jtbTipoFu.getSelectedRow(), 0));
            }
            
            if (fields.size() > 0 && jtbUpdate.getSelectedRowCount() > 0) {
                String s;
                String [] params = new String[1];
                String [] fieldsArray = new String[fields.size()];
                fields.toArray(fieldsArray);
                int [] rows = jtbUpdate.getSelectedRows();
                for ( int i = 0; i < rows.length; i++ ) {
                    try {
                        s = "funcionario.idFu="+jtbUpdate.getValueAt(rows[i],0).toString();
                        params[0] = s;
                        dbInterface.update(fieldsArray, params,
                                new String[]{"funcionario"});
                    } catch (SQLException ex) {
                        frame.printException(ex);
                        JOptionPane.showMessageDialog(null, "Não foi possível "
                                + "atualizar os dados da " + rows[i] + "linha no banco.");
                    }
                }
            } else {
                JOptionPane.showMessageDialog(null, "Você deve selecionar os "
                        + "registros a serem modificados e inserir nos campos as modificações");
            }
            
            jtbUpdate.clearSelection();
            try {
                setupTable();
            } catch (SQLException ex) {
                frame.printException(ex);
            }
            
        }
    }
    
}
